"""Utilities to keep PyQt5 and OpenCV from fighting over Qt plugin paths."""

from __future__ import annotations

import os
from pathlib import Path
from typing import Optional

from PyQt5.QtCore import QLibraryInfo


def _pyqt_plugin_path() -> Optional[str]:
    path = QLibraryInfo.location(QLibraryInfo.PluginsPath)
    if not path:
        return None
    resolved = Path(path)
    return str(resolved) if resolved.is_dir() else None


def ensure_pyqt_qt_plugin_path() -> Optional[str]:
    """Force Qt to load plugins from PyQt5 instead of the OpenCV wheel."""
    plugin_path = _pyqt_plugin_path()
    if not plugin_path:
        return None
    os.environ["QT_QPA_PLATFORM_PLUGIN_PATH"] = plugin_path
    os.environ["QT_PLUGIN_PATH"] = plugin_path
    return plugin_path


ensure_pyqt_qt_plugin_path()
import cv2 as _cv2
ensure_pyqt_qt_plugin_path()

cv2 = _cv2

__all__ = ["cv2", "ensure_pyqt_qt_plugin_path"]
